import React, { memo, useCallback, useMemo, useState } from 'react';
import { Card, Select, Button, Space, DatePicker, Radio, Tabs, Badge, Tooltip, Alert } from 'antd';
import { UserOutlined, CalendarOutlined, TableOutlined, BarsOutlined, CompressOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';

dayjs.extend(isBetween);
import type { IMixedScheduleViewProps, IMixedScheduleData, IStudentScheduleGroup } from '@/types/components/schedule';
import ScheduleInstanceCard from '../ScheduleInstanceCard';
import styles from './MixedScheduleView.module.css';

const { Option } = Select;
const { RangePicker } = DatePicker;

/**
 * 混合课表视图组件
 * @description 显示多个学生的课程表，支持不同的显示模式和智能布局
 */
const MixedScheduleView: React.FC<IMixedScheduleViewProps> = memo(({
  selectedStudents,
  scheduleInstances,
  students,
  courses,
  onStudentToggle,
  onInstanceClick,
  onDateRangeChange,
  viewMode = 'timeline',
  dateRange,
  className,
  readonly = false,
  showStudentSelector = true,
  maxStudents = 5
}) => {
  const [currentViewMode, setCurrentViewMode] = useState(viewMode);
  const [currentDateRange, setCurrentDateRange] = useState(
    dateRange || {
      start: dayjs().startOf('week').format('YYYY-MM-DD'),
      end: dayjs().endOf('week').format('YYYY-MM-DD')
    }
  );

  // 生成混合课表数据
  const mixedScheduleData = useMemo((): IMixedScheduleData => {
    // 筛选选中学生的课程实例
    const filteredInstances = scheduleInstances.filter(instance => 
      selectedStudents.includes(instance.studentId) &&
      dayjs(instance.date).isBetween(currentDateRange.start, currentDateRange.end, 'day', '[]')
    );

    // 按学生分组
    const studentGroups: IStudentScheduleGroup[] = selectedStudents.map(studentId => {
      const student = students.find(s => s.id === studentId);
      if (!student) return null;

      const studentInstances = filteredInstances.filter(instance => instance.studentId === studentId);
      const courseMap: Record<string, any> = {};
      
      studentInstances.forEach(instance => {
        const course = courses.find(c => c.id === instance.courseId);
        if (course) {
          courseMap[course.id] = course;
        }
      });

      return {
        student,
        instances: studentInstances.sort((a, b) => 
          a.date.localeCompare(b.date) || a.startTime.localeCompare(b.startTime)
        ),
        courseMap
      };
    }).filter(Boolean) as IStudentScheduleGroup[];

    // 生成时间段
    const timeSlots = Array.from(new Set(
      filteredInstances.map(instance => `${instance.startTime}-${instance.endTime}`)
    )).sort().map(timeSlot => {
      const [startTime, endTime] = timeSlot.split('-');
      return { startTime, endTime, label: timeSlot };
    });

    return {
      timeSlots,
      studentGroups,
      dateRange: currentDateRange,
      conflicts: [] // TODO: 实现冲突检测
    };
  }, [selectedStudents, scheduleInstances, students, courses, currentDateRange]);

  // 处理学生选择变化
  const handleStudentChange = useCallback((studentIds: string[]) => {
    // 限制最大选择数量
    const limitedIds = studentIds.slice(0, maxStudents);
    limitedIds.forEach(studentId => {
      onStudentToggle?.(studentId);
    });
  }, [onStudentToggle, maxStudents]);

  // 处理日期范围变化
  const handleDateRangeChange = useCallback((dates: any) => {
    if (dates && dates.length === 2) {
      const start = dates[0].format('YYYY-MM-DD');
      const end = dates[1].format('YYYY-MM-DD');
      setCurrentDateRange({ start, end });
      onDateRangeChange?.(start, end);
    }
  }, [onDateRangeChange]);

  // 处理视图模式变化
  const handleViewModeChange = useCallback((mode: string) => {
    setCurrentViewMode(mode as any);
  }, []);

  // 渲染时间轴视图
  const renderTimelineView = () => {
    if (mixedScheduleData.studentGroups.length === 0) {
      return (
        <div className={styles.emptyState}>
          <div className={styles.emptyMessage}>请选择学生查看课表</div>
        </div>
      );
    }

    return (
      <div className={styles.timelineContainer}>
        {mixedScheduleData.studentGroups.map(group => (
          <Card
            key={group.student.id}
            className={styles.studentCard}
            title={
              <div className={styles.studentHeader}>
                <UserOutlined className={styles.studentIcon} />
                <span className={styles.studentName}>{group.student.name}</span>
                <Badge count={group.instances.length} className={styles.instanceCount} />
              </div>
            }
            size="small"
          >
            <div className={styles.instanceTimeline}>
              {group.instances.length === 0 ? (
                <div className={styles.noInstances}>该时间段内无课程安排</div>
              ) : (
                <div className={styles.instanceGrid}>
                  {group.instances.map(instance => {
                    const course = group.courseMap[instance.courseId];
                    if (!course) return null;

                    return (
                      <ScheduleInstanceCard
                        key={instance.id}
                        instance={instance}
                        student={group.student}
                        course={course}
                        onEdit={() => onInstanceClick?.(instance)}
                        size="small"
                        readonly={readonly}
                        className={styles.timelineInstanceCard}
                      />
                    );
                  })}
                </div>
              )}
            </div>
          </Card>
        ))}
      </div>
    );
  };

  // 渲染网格视图
  const renderGridView = () => {
    const dates: string[] = [];
    const current = dayjs(currentDateRange.start);
    const end = dayjs(currentDateRange.end);
    
    while (current.isBefore(end) || current.isSame(end, 'day')) {
      dates.push(current.format('YYYY-MM-DD'));
      current.add(1, 'day');
    }

    return (
      <div className={styles.gridContainer}>
        <div className={styles.gridHeader}>
          <div className={styles.studentColumn}>学生</div>
          {dates.map(date => (
            <div key={date} className={styles.dateColumn}>
              <div className={styles.dateLabel}>{dayjs(date).format('MM/DD')}</div>
              <div className={styles.weekdayLabel}>{dayjs(date).format('ddd')}</div>
            </div>
          ))}
        </div>
        
        <div className={styles.gridBody}>
          {mixedScheduleData.studentGroups.map(group => (
            <div key={group.student.id} className={styles.gridRow}>
              <div className={styles.studentCell}>
                <div className={styles.studentInfo}>
                  <span className={styles.studentName}>{group.student.name}</span>
                  <Badge count={group.instances.length} size="small" />
                </div>
              </div>
              
              {dates.map(date => {
                const dayInstances = group.instances.filter(instance => instance.date === date);
                return (
                  <div key={date} className={styles.dateCell}>
                    {dayInstances.map(instance => {
                      const course = group.courseMap[instance.courseId];
                      if (!course) return null;

                      return (
                        <div
                          key={instance.id}
                          className={styles.gridInstance}
                          style={{ backgroundColor: course.color + '20', borderColor: course.color }}
                          onClick={() => onInstanceClick?.(instance)}
                        >
                          <div className={styles.instanceTime}>
                            {instance.startTime}-{instance.endTime}
                          </div>
                          <div className={styles.instanceCourse}>{course.name}</div>
                        </div>
                      );
                    })}
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    );
  };

  // 渲染紧凑视图
  const renderCompactView = () => {
    const allInstances = mixedScheduleData.studentGroups.flatMap(group => 
      group.instances.map(instance => ({
        ...instance,
        student: group.student,
        course: group.courseMap[instance.courseId]
      }))
    ).sort((a, b) => 
      a.date.localeCompare(b.date) || a.startTime.localeCompare(b.startTime)
    );

    // 按日期分组
    const groupedByDate = allInstances.reduce((acc, item) => {
      if (!acc[item.date]) {
        acc[item.date] = [];
      }
      acc[item.date].push(item);
      return acc;
    }, {} as Record<string, typeof allInstances>);

    return (
      <div className={styles.compactContainer}>
        {Object.entries(groupedByDate).map(([date, instances]) => (
          <Card
            key={date}
            className={styles.dateCard}
            title={
              <div className={styles.dateHeader}>
                <CalendarOutlined className={styles.dateIcon} />
                <span className={styles.dateTitle}>
                  {dayjs(date).format('YYYY年MM月DD日 dddd')}
                </span>
                <Badge count={instances.length} />
              </div>
            }
            size="small"
          >
            <div className={styles.compactInstances}>
              {instances.map(item => (
                <div
                  key={item.id}
                  className={styles.compactInstance}
                  onClick={() => onInstanceClick?.(item)}
                >
                  <div 
                    className={styles.compactIndicator}
                    style={{ backgroundColor: item.course.color }}
                  />
                  <div className={styles.compactContent}>
                    <div className={styles.compactTime}>
                      {item.startTime}-{item.endTime}
                    </div>
                    <div className={styles.compactInfo}>
                      <span className={styles.compactCourse}>{item.course.name}</span>
                      <span className={styles.compactStudent}>{item.student.name}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        ))}
      </div>
    );
  };

  // 渲染视图内容
  const renderViewContent = () => {
    switch (currentViewMode) {
      case 'grid':
        return renderGridView();
      case 'compact':
        return renderCompactView();
      case 'timeline':
      default:
        return renderTimelineView();
    }
  };

  return (
    <div className={`${styles.mixedScheduleView} ${className || ''}`}>
      {/* 控制面板 */}
      <Card className={styles.controlPanel} size="small">
        <div className={styles.controlContent}>
          {showStudentSelector && (
            <div className={styles.studentSelector}>
              <label className={styles.controlLabel}>选择学生：</label>
              <Select
                mode="multiple"
                value={selectedStudents}
                onChange={handleStudentChange}
                placeholder="请选择学生"
                className={styles.studentSelect}
                maxTagCount="responsive"
              >
                {students.map(student => (
                  <Option key={student.id} value={student.id}>
                    {student.name} ({student.studentId})
                  </Option>
                ))}
              </Select>
              {selectedStudents.length >= maxStudents && (
                <span className={styles.limitHint}>
                  最多选择 {maxStudents} 个学生
                </span>
              )}
            </div>
          )}

          <div className={styles.dateRangeSelector}>
            <label className={styles.controlLabel}>日期范围：</label>
            <RangePicker
              value={[dayjs(currentDateRange.start), dayjs(currentDateRange.end)]}
              onChange={handleDateRangeChange}
              format="YYYY-MM-DD"
              className={styles.dateRangePicker}
            />
          </div>

          <div className={styles.viewModeSelector}>
            <label className={styles.controlLabel}>视图模式：</label>
            <Radio.Group
              value={currentViewMode}
              onChange={(e) => handleViewModeChange(e.target.value)}
              className={styles.viewModeRadio}
            >
              <Radio.Button value="timeline">
                <BarsOutlined /> 时间轴
              </Radio.Button>
              <Radio.Button value="grid">
                <TableOutlined /> 网格
              </Radio.Button>
              <Radio.Button value="compact">
                <CompressOutlined /> 紧凑
              </Radio.Button>
            </Radio.Group>
          </div>
        </div>
      </Card>

      {/* 统计信息 */}
      {selectedStudents.length > 0 && (
        <Card className={styles.statsCard} size="small">
          <div className={styles.statsContent}>
            <div className={styles.statItem}>
              <span className={styles.statLabel}>选中学生：</span>
              <span className={styles.statValue}>{selectedStudents.length}</span>
            </div>
            <div className={styles.statItem}>
              <span className={styles.statLabel}>课程总数：</span>
              <span className={styles.statValue}>
                {mixedScheduleData.studentGroups.reduce((sum, group) => sum + group.instances.length, 0)}
              </span>
            </div>
            <div className={styles.statItem}>
              <span className={styles.statLabel}>时间段：</span>
              <span className={styles.statValue}>{mixedScheduleData.timeSlots.length}</span>
            </div>
          </div>
        </Card>
      )}

      {/* 主要内容区域 */}
      <Card className={styles.contentCard}>
        {renderViewContent()}
      </Card>
    </div>
  );
});

MixedScheduleView.displayName = 'MixedScheduleView';

export default MixedScheduleView;